<template>
  <div class="order-page-wrapper">

    <div class="order-container">
      <div class="order-search-bar">
        <el-form :inline="true" :model="orderSearchForm">
          <el-form-item label="订单状态">
            <el-select v-model="orderSearchForm.status" placeholder="全部状态" clearable style="width: 120px;">
              <el-option label="待支付" :value="0"></el-option>
              <el-option label="已支付" :value="1"></el-option>
              <el-option label="已取消" :value="2"></el-option>
              <el-option label="已完成" :value="3"></el-option>
              <el-option label="已过期" :value="4"></el-option>
              <el-option label="待退款" :value="5"></el-option>
              <el-option label="已退款" :value="6"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="预订时间">
            <el-date-picker
              v-model="orderSearchForm.bookingTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item label="金额范围">
            <div class="amount-range-wrapper">
              <el-input-number
                v-model="orderSearchForm.minAmount"
                :precision="2"
                :step="0.1"
                :min="0"
                placeholder="最小金额"
                class="amount-input"
              />
              <span class="amount-separator">-</span>
              <el-input-number
                v-model="orderSearchForm.maxAmount"
                :precision="2"
                :step="0.1"
                :min="0"
                placeholder="最大金额"
                class="amount-input"
              />
            </div>
          </el-form-item>
          <el-form-item label="会议室名称">
            <el-input
              v-model="orderSearchForm.meetingRoomName"
              placeholder="请输入会议室名称"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getOrderList">查询</el-button>
            <el-button @click="resetSearch">刷新</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-container">
        <el-table :data="orderList" border style="width: 100%" v-loading="loading">
          <el-table-column label="订单" width="180" align="center">
            <template #default="scope">
              <div style="display: flex; flex-direction: column; align-items: center; gap: 4px;">
                <span>{{ scope.row.orderNo }}</span>
                <el-tag :type="getOrderStatusType(scope.row.status)" size="small">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="会议室" width="150" align="center">
            <template #default="scope">
              <span>{{ scope.row.meetingRoomName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="预订时间" width="150" align="center">
            <template #default="scope">
              <div>{{ formatDateTime(scope.row.startTime) }}</div>
              <div style=" align-items: center;">至</div>
              <div>{{ formatDateTime(scope.row.endTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="金额" width="150" align="center">
            <template #default="scope">
              <span>{{ scope.row.totalAmount }}元（{{ scope.row.pricePerHour }}/hour）</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="150" align="center">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="其他信息" min-width="150" align="center">
            <template #default="scope">
              <div v-if="scope.row.status === 0">
                支付截止时间：{{ formatDateTime(scope.row.payExpireTime) }}
              </div>
              <div v-if="scope.row.status === 2">
                取消时间：{{ formatDateTime(scope.row.cancelTime) }}
              </div>
              <div v-if="scope.row.status === 5 && scope.row.refundAmount">
                预计退款金额：{{ scope.row.refundAmount }}元
              </div>
              <div v-if="scope.row.status === 6 && scope.row.refundAmount">
                已退款金额：{{ scope.row.refundAmount }}元
              </div>
              <div v-if="scope.row.status === 5">
                <el-button type="primary" size="small" @click="handleRefund(scope.row)">退款</el-button>
                <el-button type="text" size="small" @click="handleRefuseRefund(scope.row)">拒绝</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="orderCurrentPage"
          v-model:page-size="orderPageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="orderTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../api/request'
import dayjs from 'dayjs'
import { useStore } from 'vuex'

// 订单相关的响应式变量
const orderList = ref([])
const orderCurrentPage = ref(1)
const orderPageSize = ref(10)
const orderTotal = ref(0)
const loading = ref(false)
const store = useStore()

const orderSearchForm = ref({
  status: store.state.hasPendingRefunds ? 5 : null, // 从链接过来的才只显示待退款订单
  bookingTimeRange: null,
  minAmount: null,
  maxAmount: null,
  meetingRoomName: ''
})

// 获取会议室信息
const getMeetingRoomInfo = async (meetingRoomId) => {
  try {
    const response = await request({
      url: '/common/meeting-room',
      method: 'post',
      data: {
        id: meetingRoomId,
        date: new Date()
      }
    })
    return response.data.records[0].name
  } catch (error) {
    console.error('获取会议室信息失败：', error)
    return '未知会议室'
  }
}

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    const response = await request({
      url: '/employee/booking-order',
      method: 'post',
      data: {
        ...orderSearchForm.value,
        startTime: orderSearchForm.value.bookingTimeRange ? orderSearchForm.value.bookingTimeRange[0] : null,
        endTime: orderSearchForm.value.bookingTimeRange ? orderSearchForm.value.bookingTimeRange[1] : null,
        pageNum: orderCurrentPage.value,
        pageSize: orderPageSize.value
      }
    })
    // 获取所有订单的会议室信息
    const ordersWithRoomNames = await Promise.all(
      response.data.records.map(async (item) => ({
        ...item,
        meetingRoomName: await getMeetingRoomInfo(item.meetingRoomId)
      }))
    )
    orderList.value = ordersWithRoomNames.filter(order => {
      // 筛选金额范围
      if (orderSearchForm.value.minAmount !== null && order.totalAmount < orderSearchForm.value.minAmount) {
        return false
      }
      if (orderSearchForm.value.maxAmount !== null && order.totalAmount > orderSearchForm.value.maxAmount) {
        return false
      }
      // 筛选会议室名称
      if (orderSearchForm.value.meetingRoomName && !order.meetingRoomName.includes(orderSearchForm.value.meetingRoomName)) {
        return false
      }
      return true
    })
    .sort((a, b) => {
      if(a.status == 5 && b.status != 5) return -1
      if(a.status != 5 && b.status == 5) return 1
      return dayjs(a.createTime).valueOf() - dayjs(b.createTime).valueOf()
    })
    orderTotal.value = response.data.total
  } catch (error) {
    ElMessage.error('获取订单列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '已支付',
    2: '已取消',
    3: '已完成',
    4: '已过期',
    5: '待退款',
    6: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单状态标签类型
const getOrderStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'info',
    3: 'success',
    4: 'danger',
    5: 'warning',
    6: 'info'
  }
  return typeMap[status] || ''
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return dayjs(datetime).format('YYYY-MM-DD HH:mm')
}

// 重置搜索条件并刷新列表
const resetSearch = () => {
  orderSearchForm.value.status = null
  orderSearchForm.value.createTimeRange = null
  orderSearchForm.value.bookingTimeRange = null
  orderSearchForm.value.minAmount = null
  orderSearchForm.value.maxAmount = null
  orderSearchForm.value.meetingRoomName = ''
  getOrderList()
}

// 处理退款操作
const handleRefund = async (order) => {
  if(formatDateTime(order.startTime) < dayjs().format('YYYY-MM-DD HH:mm:ss')) {
    ElMessage.warning('会议已开始，无法退款')
    return
  }
  try {
    await ElMessageBox.confirm(
      '您确定要对该订单进行退款吗？',
      '确认退款',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request({
      url: '/employee/refund',
      method: 'put',
      params: {
        id: order.id
      }
    })
    ElMessage.success('退款成功')
    getOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退款失败：' + error.message)
    } else {
      ElMessage.info('已取消退款操作')
    }
  }finally {
    getOrderList()
  }
}

// 处理拒绝退款操作
const handleRefuseRefund = async (order) => {
  try {
    await ElMessageBox.confirm(
      '您确定要拒绝该订单的退款申请吗？',
      '确认拒绝退款',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request({
      url: '/employee/refuse-refund',
      method: 'put',
      params: {
        id: order.id
      }
    })
    ElMessage.success('已拒绝退款申请')
    getOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败：' + error.message)
    } else {
      ElMessage.info('已取消操作')
    }
  }
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  orderPageSize.value = val
  getOrderList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  orderCurrentPage.value = val
  getOrderList()
}

onMounted(() => {
  getOrderList()
})


</script>

<style scoped>
.order-page-wrapper {
  padding: 0px 9vh;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32px;
  height: 56px;
  background: #409EFF;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  border-bottom-left-radius: 12px;
  border-bottom-right-radius: 12px;
  box-shadow: 0 2px 8px #e0e3e7;
}

.nav-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.navbar-title {
  letter-spacing: 2px;
}

.logout-btn {
  font-size: 14px;
  font-weight: normal;
}

.order-container {
  padding: 32px 40px 20px 40px;
  max-width: 1500px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px #e0e3e7;
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  height: 100%;
  overflow: hidden;  /* 防止内容溢出 */
}

.table-container {
  flex: 1;
  overflow: hidden;  /* 防止表格容器本身滚动 */
  position: relative;  /* 为固定表头提供定位上下文 */
}

.table-container .el-table {
  height: 100%;  /* 让表格填满容器 */
}

/* 设置表体可滚动，表头固定 */
.table-container .el-table__body-wrapper {
  overflow-y: auto;  /* 只允许垂直滚动 */
  height: calc(100% - 48px) !important;  /* 减去表头高度 */
}

/* 确保表头固定 */
.table-container .el-table__header-wrapper {
  position: sticky;
  top: 0;
  z-index: 1;
}

.order-search-bar {
  margin-bottom: 20px;
  background: #f9fafb;
  padding: 16px;
  border-radius: 8px;
}

.amount-range-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.amount-input {
  width: 150px;
}

.amount-separator {
  color: #909399;
  font-weight: 500;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}
</style>